package com.hafu.service;
import   com.hafu.dao.RuKuDetailDao;
import com.hafu.dao.RuKuMainDao;
import com.hafu.model.KuCun;
import   com.hafu.model.RuKuDetail;
import   com.hafu.model.RuKuMain;
import com.hafu.util.DbUtil;
import java.sql.Connection;
import  java.sql.SQLException;
import  java.util.ArrayList;
public class RuKuService {
    private  RuKuMainDao  ruKuMainDao  =new  RuKuMainDao();
    private  RuKuDetailDao  ruKuDetailDao  =new  RuKuDetailDao();
    private  KuCunService  kuCunService=new KuCunService();
    public  boolean  addRuKu(RuKuMain  ruku)
    {
        Connection conn =DbUtil.getConnection();
        try  {
        conn.setAutoCommit(false);
        int i=ruKuMainDao.addRuKuMain(ruku,conn);
        if (i>0){
            ArrayList<RuKuDetail> rukudetailList  =ruku.getRukudetaillist();
            for (RuKuDetail rukuDetail :rukudetailList){
                rukuDetail. setRukuld(ruku.getld());
                boolean        b=ruKuDetailDao.addRuKuDetail(rukuDetail,conn);
                if (!b){
                    conn.rollback();
                    return false;
                }
                KuCun   kuCunBySpName    =kuCunService.getKuCunBySpName(rukuDetail.getSpName(),conn);
                if   (kuCunBySpName   ==null){     KuCun  kuCun  =new  KuCun();
                    kuCun.setSpname(rukuDetail.getSpName());
                    kuCun.setNum(rukuDetail.getNum());
                    boolean       b1=kuCunService.addKuCun(kuCun,conn);
                    if (!b1){
                        conn.rollback(); return false;

                    }
                }else  {
                    int        num=kuCunBySpName.getNum()+rukuDetail.getNum(); kuCunBySpName.setNum(num);
                    boolean       b1=kuCunService.updateKuCun(kuCunBySpName,conn);
                    if (!b1){
                        conn.rollback(); return false;
                    }
                }
            }
            conn.commit();
            conn.setAutoCommit(true);
            return true;
        }else {
            conn.rollback();
            return false;
        }
    }catch(SQLException    throwables){ throwables.printStackTrace();
    }
        return false;
    }
    public ArrayList<RuKuMain>getRuKuList(RuKuMain  ruku) {
        return  ruKuMainDao.getRuKuMainByName(ruku);
    }
    public  Boolean  updateRuKu(RuKuMain  rukuMain){
        return ruKuMainDao.updateRuKu(rukuMain);

    }
}
